package com.medical.patient.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.medical.common.constant.RedisLoginKey;
import com.medical.common.utils.JwtUtil;
import com.medical.patient.vo.DiagnosemanagementVo;
import com.medical.patient.vo.DiagnosemanagementparticularsVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.medical.patient.controller.vo.ReceptionVo;
import com.medical.patient.feign.InquiyFeignClient;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import com.medical.patient.entity.PatientMedicalRecordEntity;
import com.medical.patient.service.PatientMedicalRecordService;
import com.medical.common.utils.PageUtils;
import com.medical.common.utils.R;

import javax.servlet.http.HttpSession;


/**
 * 
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2021-08-13 18:42:36
 */
@RestController
@RequestMapping("patient/patientmedicalrecord")
public class PatientMedicalRecordController {
    @Autowired
    private PatientMedicalRecordService patientMedicalRecordService;

    @Autowired
    private InquiyFeignClient client;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 诊断报告/
     */
    @GetMapping("diagnosticReport/{recordId}")
    public PatientMedicalRecordEntity diagnosticReport(
            @PathVariable("recordId") Integer recordId
    ){
        return patientMedicalRecordService.diagnosticReport(recordId);
    }

    /**
     * 开/关闭医生接诊
     * */
    @PostMapping("/inquiry")
    public String inquiry(@RequestParam("inquiry") Integer inquiry,
                          @RequestParam("doctorId")Integer doctorId){
        return client.inquiry(inquiry,doctorId);
    }

    /**
     * 医生接诊台列表
     * */
    @PostMapping("ReceptionList")
    public R ReceptionList(
            @RequestParam (value = "page",defaultValue = "1") Integer page,
            @RequestParam(value = "size",defaultValue = "3") Integer size,
            @RequestBody ReceptionVo vo,
            HttpSession session,
            @RequestHeader(value = "token")String token
    ){
        //有token的值，说明已经登陆过了
        if(StringUtils.isNotEmpty(token)){
            Set<String> keys = redisTemplate.keys(RedisLoginKey.DOCTOR_ROLE.keyPrefix+"*");
            if(keys!=null&&keys.size()>0){//有人正在登录
                for (String key : keys) {
                    String[] split = key.split(":");
                    if(split[2].equals(token)){//验证令牌通过
                        //开始鉴权
                        Claims claims = jwtUtil.parseJWT(token);
                        String role = (String) claims.get("roles");
                        if(role.equals("医生")){
                            String s = redisTemplate.opsForValue().get(RedisLoginKey.DOCTOR_ROLE.keyPrefix + token);//获得用户的信息
                            session.setAttribute("loginuser",s);
                            IPage<ReceptionVo> receptionVoIPage = patientMedicalRecordService.ReceptionList(vo, page, size);
                            PageUtils pageUtils = new PageUtils(receptionVoIPage.getRecords(),(int) receptionVoIPage.getTotal(),(int) receptionVoIPage.getSize(),(int) receptionVoIPage.getCurrent());
                            return R.ok().put("page",pageUtils);
                        }else {
                            return R.error("权限不足，无法访问");
                        }
                    }
                }
            }
            return R.ok("登录失败").put("tologin","http://127.0.0.1:5501/login.html");
        }else {//未登录，或者，跨服务登录了，让他去到sso系统鉴定
            String url="http://localhost:12000/user/member/toLogin" + "?url=http://127.0.0.1:5500/index.html";
            return R.error().put("url",url);
        }
    }


    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = patientMedicalRecordService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * userid查询患者就诊信息
     */
    @RequestMapping("/patientMedicalRecordEntityByUserId/{userId}")
    public R patientMedicalRecordEntityByUserId(@PathVariable("userId") String userId){
        List<PatientMedicalRecordEntity> patientMedicalRecordEntityList = patientMedicalRecordService.patientMedicalRecordEntityByUserId(userId);
        return R.ok().put("patientMedicalRecordEntityList", patientMedicalRecordEntityList);
    }

//    /**
//     * userid查询患者就诊信息
//     */
//    @RequestMapping("/findByUserId/{userId}")
//    public List<PatientMedicalRecordEntity> findByUserId(@PathVariable("userId") String userId){
//        List<PatientMedicalRecordEntity> patientMedicalRecordEntityList = patientMedicalRecordService.getByUserId(userId);
//
//        return  patientMedicalRecordEntityList;
//    }

    /**
     * 根据医师id查询医师对应患者的就诊信息
     */
    @RequestMapping("/findByDoctorId/{doctorId}")
    public R findByDoctorId(@PathVariable("doctorId") Integer doctorId){
        List<PatientMedicalRecordEntity> patientMedicalRecordEntityList = patientMedicalRecordService.patientMedicalRecordEntityByDoctorId(doctorId);
        return R.ok().put("patientMedicalRecordEntityList", patientMedicalRecordEntityList);
    }

    /**
     * userid查询患者就诊信息
     */
    @RequestMapping("/findByUserId/{userId}")
    public R findByUserId(@PathVariable("userId") String userId){
        List<PatientMedicalRecordEntity> patientMedicalRecordEntityList = patientMedicalRecordService.getByUserId(userId);

        return R.ok().put("patientMedicalRecordEntityList", patientMedicalRecordEntityList);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{recordId}")
    public R info(@PathVariable("recordId") Integer recordId){
		PatientMedicalRecordEntity patientMedicalRecord = patientMedicalRecordService.getById(recordId);

        return R.ok().put("patientMedicalRecord", patientMedicalRecord);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody PatientMedicalRecordEntity patientMedicalRecord){
		patientMedicalRecordService.save(patientMedicalRecord);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody PatientMedicalRecordEntity patientMedicalRecord){
		patientMedicalRecordService.updateById(patientMedicalRecord);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] recordIds){
		patientMedicalRecordService.removeByIds(Arrays.asList(recordIds));

        return R.ok();
    }

    /**
     * 诊断管理列表
     */
    @RequestMapping("/diagnosemanagement/{doctorId}")
    public R diagnosemanagement(@RequestBody DiagnosemanagementVo vo, @PathVariable("doctorId") Integer doctorId,HttpSession session){
        List<DiagnosemanagementVo> diagnosemanagementVoList = patientMedicalRecordService.diagnosemanagementList(vo,doctorId);
        return R.ok().put("diagnosemanagementVoList", diagnosemanagementVoList);
    }

    /**
     * 当天患者详细信息
     */
    @RequestMapping("/diagnosemanagementparticulars/{doctorId}/{time}")
    public R diagnosemanagementparticulars(@RequestBody DiagnosemanagementparticularsVo vo, @PathVariable("doctorId") Integer doctorId, @PathVariable("time") String time){
        List<DiagnosemanagementparticularsVo> diagnosemanagementparticularsVoList = patientMedicalRecordService.diagnosemanagementparticularsList(vo,doctorId,time);


        return R.ok().put("diagnosemanagementparticularsVoList", diagnosemanagementparticularsVoList);
    }

}
